package com.xwdeshj.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.ObjectMetadata;
import com.xwdeshj.service.XwBannerService;
import com.xwdeshj.utils.DownloadAndCompression;
import com.xwdeshj.utils.IMoocExceptionHandler;
import com.xwdeshj.utils.aliyun.OSSClientConstants;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.thymeleaf.util.StringUtils;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by BKWJA on 2018/11/22.
 * 图片文件上传
 */
@Api(value = "UploadController",tags = "文件上传接口类")
@Slf4j
@Controller
@CrossOrigin(allowCredentials = "true")
@RequestMapping("xw")
public class UploadController extends IMoocExceptionHandler {

    @Autowired
    private XwBannerService xwBannerService;

    //阿里云API的内或外网域名
    private static String ENDPOINT;
    //阿里云API的密钥Access Key ID
    private static String ACCESS_KEY_ID;
    //阿里云API的密钥Access Key Secret
    private static String ACCESS_KEY_SECRET;
    //阿里云API的bucket名称
    private static String BACKET_NAME;
    //阿里云API的文件夹名称
    private static String FOLDER;
    //需要替代的访问前缀
    private static String Accessprefix;
    //返回图片url前缀
    private static String BucketPrefix;

    //初始化属性
    static {
        ENDPOINT = OSSClientConstants.ENDPOINT;
        ACCESS_KEY_ID = OSSClientConstants.ACCESS_KEY_ID;
        ACCESS_KEY_SECRET = OSSClientConstants.ACCESS_KEY_SECRET;
        BACKET_NAME = OSSClientConstants.BACKET_NAME;
        FOLDER = OSSClientConstants.FOLDER;
        Accessprefix = OSSClientConstants.Accessprefix;
        BucketPrefix = OSSClientConstants.BucketPrefix;
    }

    /**
     * 单图上传--原图上传(简单上传)
     * 阿里云数据存储 OSS
     * @param file
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "XW_OSS存储文件上传")
    @ApiImplicitParam(name = "MultipartFile",value = "文件流")
    @RequestMapping(value = "/imgfile", produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String picOSS(@RequestParam("file") MultipartFile file) throws Exception {
        Map<String, Object> value = new HashMap<String, Object>();
        String fileext = ""; // 后缀名
        String filename = ""; // 文件名
        String newFileName = ""; //文件名+后缀名

        if (!file.isEmpty()) {

            long size = file.getSize();//获取文件大小

            // 创建OSSClient实例
            OSSClient ossClient = new OSSClient(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);

            //设置当天上传的文件自动创建 yyyy-MM-dd 的文件夹
            Date date = new Date();
            String datefilepath = new SimpleDateFormat("yyyy-MM-dd").format(date)+"/";

            String fileName = file.getOriginalFilename(); //获取上传时的文件名+后缀名
            fileext = fileName.substring(fileName.lastIndexOf(".") + 1); //获取上传的文件的后缀名

//            filename = UUID.randomUUID().toString(); //保证上传的图片名称不会重复
            filename = String.valueOf(new Date().getTime());
            filename = URLEncoder.encode(filename, "utf-8");
            newFileName = filename + "." + fileext; //文件名+后缀名
            String upladPath = FOLDER + datefilepath + newFileName; //需要保存的文件的 路径（ 文件夹+文件 ）
            try {
                //上传文件
                ossClient.putObject(BACKET_NAME, upladPath, new ByteArrayInputStream(file.getBytes()));
                // 关闭client
                ossClient.shutdown();

                Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 10);
                //获取上传文件的url
                String fileurl = ossClient.generatePresignedUrl(BACKET_NAME, upladPath, expiration).toString();
                if(!"".equals(fileurl)){
                    fileurl = fileurl.replace(BucketPrefix,Accessprefix);
                    fileurl = fileurl.substring(0,fileurl.lastIndexOf("?"));
                }

                if (fileurl != "" || fileurl != null) {
                    value.put("status", 0);
                    value.put("msg", "图片上传成功");
                    value.put("fileurl", fileurl);
                    value.put("fileext", fileext);
                    value.put("filename", newFileName);
                }
            } catch (Exception e) {
                e.printStackTrace();
                value.put("stats", 500);
                value.put("msg", "图片上传失败");
            }
        }
        return JSONObject.toJSONString(value);
    }





    /**
     * 图片转base64字符串
     * @param imgFile 图片路径
     * @return
     */
//    public static String imageToBase64Str(String imgFile){
//        InputStream inputStream = null;
//        byte[] data = null;
//        try {
//            inputStream = new FileInputStream(imgFile);
//            data = new byte[inputStream.available()];
//            inputStream.read(data);
//            inputStream.close();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        // 加密
//        BASE64Encoder encoder = new BASE64Encoder();
//        return encoder.encode(data);
//    }


    /**
     * base64编码字符串转换为图片
     * @param imgStr base64编码字符串
     * @param path 图片路径
     * @return
     */
//    public static boolean base64StrToImage(String imgStr, String path) {
//        if (imgStr == null)
//            return false;
//        BASE64Decoder decoder = new BASE64Decoder();
//        try {
//            // 解密
//            byte[] b = decoder.decodeBuffer(imgStr);
//            // 处理数据
//            for (int i = 0; i < b.length; ++i) {
//                if (b[i] < 0) {
//                    b[i] += 256;
//                }
//            }
//            //文件夹不存在则自动创建
//            File tempFile = new File(path);
//            if (!tempFile.getParentFile().exists()) {
//                tempFile.getParentFile().mkdirs();
//            }
//            OutputStream out = new FileOutputStream(tempFile);
//            out.write(b);
//            out.flush();
//            out.close();
//            return true;
//        } catch (Exception e) {
//            return false;
//        }
//    }


    /**
     * 打包下载文件  根据id获取素材信息
     * @return
     * @throws UnsupportedEncodingException
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("downloadSourceMaterial")
    public void downloadSourceMaterial(String Id, HttpServletResponse resp, HttpServletRequest req) throws UnsupportedEncodingException {
		/*url=new String(Base64.getDecoder().decode(url.replaceAll(" ","+")),"utf-8");
		System.out.println(url);*/
        //获取url
        String url = "";
        JSONObject sourceMaterialInfo = (JSONObject) xwBannerService.getBannerByEncryptId(Id);
        @SuppressWarnings("unchecked")
        JSONArray list = sourceMaterialInfo.getJSONArray("list");
        for (int i = 0; i < list.size(); i++) {
            Map<String, Object> map = (Map<String, Object>) list.get(i);
            if (url.equals("")) {
                url += URLDecoder.decode((String) map.get("url"),"UTF-8") + "|" +  URLDecoder.decode((String)map.get("title"),"UTF-8");
            } else {
                url += "," +  URLDecoder.decode((String)map.get("url"),"UTF-8") + "|" +  URLDecoder.decode((String)map.get("title"),"UTF-8");
            }
        }
        System.out.println(url);
        String downloadFolder = req.getServletContext().getRealPath("/") + "excel/" + new Date().getTime() + (int) (Math.random() * 10);

        ServletOutputStream outputStream = null;
        File folder = new File(downloadFolder);
        folder.mkdirs();
        try {
            resp.setCharacterEncoding("utf-8");
            resp.setContentType("multipart/form-data");
            resp.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("素材" + new Date().getTime() + ".zip", "utf-8"));
            DownloadAndCompression.downLoad(url, downloadFolder);
            outputStream = resp.getOutputStream();
            DownloadAndCompression.toZip(downloadFolder, outputStream, true);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (outputStream != null) {
                    outputStream.close();
                }
                if (folder.exists()) {
                    deleteDirectory(folder);
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }

    // 删除文件夹
    private static void deleteDirectory(File file) {
        if (file.isFile()) {// 表示该文件不是文件夹
            file.delete();
        } else {
            // 首先得到当前的路径
            String[] childFilePaths = file.list();
            for (String childFilePath : childFilePaths) {
                File childFile = new File(file.getAbsolutePath() + "/" + childFilePath);
                deleteDirectory(childFile);
            }
            file.delete();
        }
    }


}
